import { useEffect, useRef } from "react";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Header from "./Header";

export default function ImportList() {

  const container = useRef();

  /**
   * THREE 三大要素：场景（scene）、相机（camera）、渲染器（renderer）
   *    使用相机将场景渲染到网页上
   */
  const scene = useRef(new THREE.Scene()); // 场景
  const camera = useRef(null); // 相机
  const renderer = useRef(new THREE.WebGLRenderer()); // 渲染器

  const mesh = useRef(null); // 网格

  // 初始化渲染
  function initRenderer() {
    if (!container.current) {
      return false;
    }
    renderer.current.setSize(1000, 800);
    renderer.current.domElement.style.position = "absolute";
    renderer.current.domElement.style.top = "0";
    renderer.current.domElement.style.left = "0";
    renderer.current.domElement.style.right = "0";
    renderer.current.domElement.style.bottom = "0";
    renderer.current.domElement.style.margin = "auto";
    container.current.appendChild(renderer.current.domElement);
  }

  // 初始化相机
  function initCamera() {
    camera.current = new THREE.PerspectiveCamera( // 透视相机
      75,
      container.current.offsetWidth / container.current.offsetHeight,
      0.1,
      1000
    );
    camera.current.position.set(15.967, -306.948, 107.634);
    camera.current.lookAt(new THREE.Vector3(0, 0, 0));
  }

  // 将图形和材质添加到网格里，将网格添加到场景中
  function initMesh() {
    const geometry = new THREE.BoxGeometry(100, 100, 100);
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    mesh.current = new THREE.Mesh(geometry, material);
    scene.current.add(mesh.current);
  }

  // 渲染
  function render() {
    // 旋转
    mesh.current.rotation.x += 0.01;
    mesh.current.rotation.y += 0.01;
    // 使用相机将场景渲染到网页上
    renderer.current.render(scene.current, camera.current);

    // 重绘
    requestAnimationFrame(render);
  }

  useEffect(() => {
    initRenderer();
    initCamera();
    initMesh();
    render();
    return () => {
      container.current?.removeChild(renderer.current.domElement);
    };
  }, []);

  return (
    <>
    <Header />
      <div
        ref={container}
        style={{
          width: "100%",
          height: "100%",
          position: "relative",
        }}
      />
    </>
  );
}
